package org.smallmind.scribe.pen;

import java.util.LinkedList;
import java.util.regex.Matcher;
import org.smallmind.scribe.pen.nutsnbolts.util.DotNotation;
import org.smallmind.scribe.pen.nutsnbolts.util.DotNotationException;

public class ClassNameTemplate extends Template {

   private DotNotation notation;

   public ClassNameTemplate (String patternString)
      throws LoggerException {

      super();

      try {
         notation = new DotNotation(patternString);
      }
      catch (DotNotationException dotNotationException) {
         throw new LoggerException(dotNotationException);
      }
   }

   public ClassNameTemplate (Level level, boolean autoFillLogicalContext, String patternString)
      throws LoggerException {

      super(level, autoFillLogicalContext);

      try {
         notation = new DotNotation(patternString);
      }
      catch (DotNotationException dotNotationException) {
         throw new LoggerException(dotNotationException);
      }
   }

   public ClassNameTemplate (Filter[] filters, Appender[] appenders, Enhancer[] enhancers, Level level, boolean autoFillLogicalContext, String patternString)
      throws LoggerException {

      super(filters, appenders, enhancers, level, autoFillLogicalContext);

      try {
         notation = new DotNotation(patternString);
      }
      catch (DotNotationException dotNotationException) {
         throw new LoggerException(dotNotationException);
      }
   }

   public int matchLogger (String loggerName) {

      Matcher matcher;
      Integer[] dotPositions;
      int matchValue = NO_MATCH;

      dotPositions = getDotPositions(loggerName);
      matcher = notation.getPattern().matcher(loggerName);

      if (matcher.matches()) {
         matchValue += 2;
         for (int count = 1; count <= matcher.groupCount(); count++) {
            matchValue += assignValueToMatch(dotPositions, matcher.start(count));
         }
      }

      return matchValue;
   }

   public static int assignValueToMatch (Integer[] dotPositions, int matchStart) {

      int index = 0;

      for (Integer dotPosition : dotPositions) {
         if (dotPosition > matchStart) {
            break;
         }
         index++;
      }

      return (int)Math.pow(2, index);
   }

   public static Integer[] getDotPositions (String loggerName) {

      Integer[] dotPosiitions;
      LinkedList<Integer> dotPositionList;

      dotPositionList = new LinkedList<Integer>();
      for (int count = 0; count < loggerName.length(); count++) {
         if (loggerName.charAt(count) == '.') {
            dotPositionList.add(count);
         }
      }

      dotPosiitions = new Integer[dotPositionList.size()];
      dotPositionList.toArray(dotPosiitions);

      return dotPosiitions;
   }
}